package com.smg.crm.settings.service.impl;

import com.smg.crm.exception.LoginException;
import com.smg.crm.settings.dao.UserDao;
import com.smg.crm.settings.domain.User;
import com.smg.crm.settings.service.UserService;
import com.smg.crm.utils.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Project Name: Crm2
 * File Name: UserServiceImpl
 *
 * @version 1.0
 * @author:wenerduo
 * @Date: 2021/07/15/17:23
 * Copyright (c) 2021,
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public User login(String loginAct, String md5, String ipAddr) throws LoginException {

        User user = userDao.login(loginAct,md5);

        if(user == null){
            //没有查询出来,证明用户名或密码错误
            throw new LoginException("用户名或密码错误");
        }

        //失效时间,如果为空,代表永久有效
        String expireTime = user.getExpireTime();

        if(expireTime != null){
            //将当前时间和现在时间进行匹配,如果大于证明可以使用,如果小于证明已失效

            if(expireTime.compareTo(DateTimeUtil.getSysTime()) < 0){
                //已失效
                throw new LoginException("账号已过期");
            }

        }

        //锁定状态,0锁定,1启用
        String lockState = user.getLockState();

        if("0".equals(lockState)){
            //账号锁定
            throw new LoginException("账号已过期,请联系管理员");
        }

        //判断ip地址是否受限
        //192.168.1.1,192.168.1.2,192.168.1.3,127.0.0.1
        String allowIps = user.getAllowIps();

        if(allowIps != null) {
            //可以进行字符串的切割,获取切割后的数据,然后进行ip地址的匹配
//        String[] ips = allowIps.split(",");
//        for (String allowIp : ips) {
//            if(!allowIp.equals(ipAddr)){
//                throw new LoginException("IP地址受限");
//            }
//        }

            //也可以通过字符串的方法去进行匹配,contains,匹配或包含某些ip地址
            if (!allowIps.contains(ipAddr)) {
                throw new LoginException("IP地址受限");
            }
        }

        return user;
    }

    public static void main(String[] args) {

        String expireTime1 = "2018-10-10 10:10:10";

        //获取当前时间的,年月日时分秒
        String now = DateTimeUtil.getSysTime();

        //失效时间和当前时间匹配,已过期,-1
        int i = expireTime1.compareTo(now);
        System.out.println(i);

        //失效时间和当前时间匹配,未过期,1
        String expireTime2 = "2021-10-10 10:10:10";
        int j = expireTime2.compareTo(now);
        System.out.println(j);

    }
}